package com.douqu.game.core.netty;

import com.douqu.game.core.controller.PlayerController;
import com.douqu.game.core.e.E_ServerType;
import com.douqu.game.core.protobuf.SGMainProto;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;

import java.nio.ByteOrder;

/**
 * Created by Administrator on 2017/3/15.
 */
public class NettyConnection
{
    private int id;

    private Channel channel;

    private E_ServerType serverType;

    private PlayerController playerController;

    public NettyConnection(Channel channel)
    {
        this.id = hashCode();
        this.channel = channel;
    }

    public void sendMsg(int msgID, byte[] data)
    {
        final ByteBuf byteBuf = Unpooled.buffer();

        if(ByteOrder.nativeOrder().toString().equals(ByteOrder.LITTLE_ENDIAN.toString())){
            byteBuf.writeIntLE(data==null?0:data.length);//总包长
            byteBuf.writeShortLE(msgID);//长度为2
        }else{
            byteBuf.writeInt(data==null?0:data.length);//总包长
            byteBuf.writeShort(msgID);//长度为2
        }

        if(data != null)
            byteBuf.writeBytes(data);

        ChannelFuture cf = channel.writeAndFlush(byteBuf);
//        cf.addListener(new ChannelFutureListener(){
//            @Override
//            public void operationComplete(ChannelFuture future) throws Exception {
//                System.out.println("发送完成..."+byteBuf.readableBytes());
//            }
//        });


    }

    public void destroy()
    {
        if(channel == null)
            return;

        channel.close();

        playerController = null;
    }


    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Channel getChannel() {
        return channel;
    }

    public void setChannel(Channel channel) {
        this.channel = channel;
    }

    public E_ServerType getServerType() {
        return serverType;
    }

    public void setServerType(E_ServerType serverType) {
        this.serverType = serverType;
    }

    public PlayerController getPlayerController() {
        return playerController;
    }

    public void setPlayerController(PlayerController playerController) {
        this.playerController = playerController;
    }

    @Override
    public String toString() {
        return "NettyConnection{" +
                "channel=" + channel.remoteAddress() +
                ", id=" + id +
                ", serverType=" + serverType +
                '}';
    }


}
